#include <stdio.h>
#include <boost/bind.hpp>
#include "../mars/latch.h"
#include "../mars/thread_pool.h"
#include "../mars/logger.h"

using namespace mars;

Latch latch[4];

void task(char task_name) {
    int cur_task_num = task_name - 'A';
    int consume = 0;
    for(;;) {
        // 等待门闩被打开
        // 这里 wait 的语义是 wait if close，即门闩如果是打开的，则不会 wait
        latch[cur_task_num].wait();
        // 自己关闭门闩
        latch[cur_task_num].close();

        // 模拟耗时任务
        srand(time(0) + cur_task_num);
        // 随机延时 500 ~ 2500 ms
        consume = 500 + rand() % 2000;
        usleep(consume * 1000);

        INFO_PRINT("%s:%c consume:%d ms\n", CurrentThread::name(), task_name, consume);

        // 打开下一个门闩
        latch[(cur_task_num + 1) % 4].open();
    }
}

int main() {
    ThreadPool pool;
    pool.start(4);
    pool.run(boost::bind(task, 'A'));
    pool.run(boost::bind(task, 'B'));
    pool.run(boost::bind(task, 'C'));
    pool.run(boost::bind(task, 'D'));

    latch[0].open();

    for(;;) {
        sleep(1);
    }

    return 0;
}
